package com.conorroche.taskmanagement;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class TasksHelper {

	/**
	 * @param args
	 */
	TasksHelper(Context ctx, ListView l) {
		context = ctx;
		list = l;
	}
	public void getTaskView(){	
		DBAdapter db = new DBAdapter(context);
		db.open();
		
		Cursor allTasks = db.getAllTasks();
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		if (allTasks.getCount() > 0){
			tasks = new String[allTasks.getCount()];
			taskIds = new int[allTasks.getCount()];
			int count = 0;
			allTasks.moveToFirst();
			while(!allTasks.isAfterLast()){
				taskIds[count] = allTasks.getInt(allTasks.getColumnIndex("_id"));
				Calendar taskDate = Calendar.getInstance();
				String[] date = allTasks.getString(allTasks.getColumnIndex("date")).split("/");
				String[] time = allTasks.getString(allTasks.getColumnIndex("time")).split(":");
				taskDate.set(Integer.parseInt(date[2]), (Integer.parseInt(date[1]) -1), Integer.parseInt(date[0]),
						Integer.parseInt(time[0]), Integer.parseInt(time[1]));
				String dueDate = date[0] + " " + taskDate.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()) + " " +
						time[0] + ":" + time[1];
				Map<String, String> datum = new HashMap<String, String>(2);
				datum.put("title", allTasks.getString(allTasks.getColumnIndex("name")));
				datum.put("due", "Due: " + dueDate);
				data.add(datum);
				allTasks.moveToNext();
				count++;
			}
			SimpleAdapter adapter = new SimpleAdapter(context, data, android.R.layout.simple_expandable_list_item_2,
                    new String[] {"title", "due"}, new int[] {android.R.id.text1, android.R.id.text2});
			list.setAdapter(adapter);
		}else{
			Toast.makeText(context, "There are no tasks present\nTo add one click the plus button above.", Toast.LENGTH_LONG).show();
			//Don't create a list view instead say there are no tasks
		}
		db.close();
	}
	public ListView getList(){
		return list;
	}
	public int[] getTaskIds(){
		return taskIds;
	}
	public void updateAdapter(String n){
	//	adapter = null;
		getTaskView();
	}

	private  ListView list;
	private Context context;
	private String[] tasks;
	private int[] taskIds;
}
